<?php

namespace App\Http\Middleware;

use App\Common\ErrorCode\ErrorCode;
use App\Exceptions\BusinessException;
use App\Http\Service\UserService;
use Closure;

/**
 * 检察用户主体类型是否进行方法操作
 * 该中间件依赖于UserService中的静态变量$userInfo,故使用前需要卡欧该属性值的问题
 * Class WebCheckUserTypeMiddle
 * @package App\Http\Middleware
 */
class WebCheckUserTypeMiddle
{
    /**
     * @param $request
     * @param Closure $next
     * @param $type int 希望匹配的类型
     * @return mixed
     * @throws BusinessException
     */
    public function handle($request, Closure $next, $type)
    {
        $user = UserService::getUserInfo();
        if (empty($user)) {
            throw new BusinessException(ErrorCode::ERROR_USER_UNDEFINED, '用户信息不存在');
        }

        if($user['type'] != $type){
            throw new BusinessException(ErrorCode::ERROR_USER_NO_PERMISSION, '用户注册的主体类型无法进行该操作');
        }

        return $next($request);
    }
}
